<template>
    <!-- 顶部导航栏 -->
    <NavBar navbarTitle="购物车"></NavBar>
    <!-- 底部tabBar -->
    <TabBar></TabBar>
    <!-- 购物车页的内容 -->
    <div class="cart-page">
      <!-- 未登录状态 -->
      <div class="cart-page-noLogin" v-if="false">
        <span class="noLogin-info">登录后可查看购物车中的商品</span>
        <Button class="noLogin-button" type="success" @click="login_btn">去登陆</Button>
      </div>
      <!-- 登录状态 -->
      <template v-else>
        <!-- 购物车内容 -->
        <div class="cart-page-login">
          <div class="login-cart-list">
            <div class="cart-list-info">
              <div class="info-left">
                <span class="info-icon">满减</span>
                <span class="info-txt">满一件,即可享受九折优惠</span>
              </div>
              <div class="info-right">
                <span :class="cartState === 0 ? 'right-tip' : 'right-tip active' " @click="cartStateChange">{{ cartState === 0 ? '管理' : '退出管理' }}</span>
              </div>
            </div>
            <div class="cart-list-content" v-if="cartList.length > 0">
              <!-- 每一项商品 -->
              <div class="cart-list-content-item" v-for="item,index in cartList" :key="index">
                <Checkbox v-model="item.cartSelected" @click="changeSelected_btn(item)"></Checkbox>
                <img :src="item.commodityImgs.split(',')[0]" @click="goDetail_btn(item.cartCommodityId)" alt="商品图片" title="图片">
                <div class="item-product-info">
                  <div class="info-desc">{{ item.commodityName }}</div>
                  <div class="info-attr">{{ item.commodityAttrName }}</div>
                  <div class="info-other">
                    <span class="other-price">￥{{ item.commodityAttrPrice.toFixed(2) }}</span>
                    <div class="info-change-num">
                      <span class="num-increase" @click="increaseNum_btn(item)">+</span>
                      <input type="text" v-model="item.cartCommodityCount">
                      <span class="num-reduce" @click="reduceNum_btn(item)">-</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="cart-list-content no-list" v-else>
              <span class="tip">购物车中没有商品哦~快去加购吧</span>
            </div>
          </div>
        </div>
        <!-- 底部固定功能区:全选、总价、提交订单 -->
        <div class="cart-page-bar">
          <div class="bar-radio">
            <Checkbox v-model="allSelected" @click="allSelectedChange_btn">全选</Checkbox>
          </div>
          <template v-if="cartState === 0">
            <div class="bar-total">
              <span class="total-tip">合计(￥):</span>
              <span class="total-text">{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="bar-btn">
              <van-button class="btn-amount" type="primary" :disabled="selectedProductNum === 0" @click="submitOrder_btn">去结算({{ selectedProductNum }})</van-button>
            </div>
          </template>
          <template v-else>
            <div class="bar-btns">
              <van-button class="btn-item" plain type="primary" size="small">分享</van-button>
              <van-button class="btn-item" plain type="primary" size="small">移入收藏</van-button>
              <van-button class="btn-item" type="warning" size="small" @click="deleteCartItem_btn">删除</van-button>
            </div>
          </template>
        </div>
      </template>
    </div>
</template>

<script setup lang='ts'>
import NavBar from '@/components/NavBar/NavBar.vue';
import TabBar from '@/components/TabBar/TabBar.vue';
//引入vant4组件
import { Button, Checkbox, Button as VanButton, showToast, showConfirmDialog } from "vant";
//引入vue选项式api
import { ref, onMounted, onBeforeUnmount, onDeactivated, onActivated } from "vue";
//引入路由相关
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
//@ts-ignore引入用户仓库
import { useUserStore } from "@/store/userStore.ts";
const userStore = useUserStore();
//@ts-ignore引入请求函数
import { reqUserCartList, reqUpdateUserCart, reqUpdateUserCartSelectedBatch, reqDeleteUserCartBatch } from "@/api/cart/index.ts";
//引入全局通信事件总线mitt
import mitt from "@/utils/eventBus";

//购物车相关数据
let cartList = ref([]);
//购物车状态:非管理状态 | 管理状态  默认非管理状态
let cartState = ref(0);
//底部固定功能区相关
let allSelected = ref(true);  //全选按钮
let totalPrice = ref(0);  //总价
let selectedProductNum = ref(0);  //商品/订单结算数量

//去登陆按钮
const login_btn = () => {
  router.push("/login");
}

//请求当前用户的所有购物车数据
async function getUserCartList () {
  //@ts-ignore获取用户id
  let userId = userStore.userInfo.id || JSON.parse(localStorage.getItem("userInfo")).id;
  //发请求获取购物车数据
  let res = await reqUserCartList(userId);
  if(res.code === 200){
    cartList.value = res.result;
    showToast({message:"购物车数据获取成功!",position:"top"});
  }
  console.log("获取用户购物车数据api",res);
  //执行相应的计算结果函数
  calculateUserCart();
}

//点击商品图片跳转到商品详情页
const goDetail_btn = (goodsId:number) => {
  router.push({path:"/detail",query:{goodsId:goodsId}});
}

//管理与退出管理文字按钮
function cartStateChange () {
  if(cartState.value){
    cartState.value = 0;
  } else {
    cartState.value = 1;
  }
}

//购物车是否全选、总价计算、每一项选择、商品数量增减处理函数
const calculateUserCart = () => {
  let list = cartList.value;
  allSelected.value = true;  //全选复选框置为true
  let total = 0;  //初始总价0
  let selectedNum = 0;  //选择的商品数量
  for(let i = 0; i < list.length; i ++) {
    if(!list[i].cartSelected){
      allSelected.value = false;
    } else {
      //总价累加
      total += (list[i].cartCommodityCount * list[i].commodityAttrPrice);
      selectedNum ++;
    }
  }
  totalPrice.value = total;  //赋值总价
  selectedProductNum.value = selectedNum;  //数量赋值
}

//购物车数量增减操作
async function reduceNum_btn (cartItem:any) {
  if(cartItem.cartCommodityCount === 1) return;
  cartItem.cartCommodityCount --;
  let params = {id:cartItem.id,cartCommodityCount:cartItem.cartCommodityCount};
  let res = await reqUpdateUserCart(params);
  if(res.code === 200){
    //数量修改成功,重新计算数据
    calculateUserCart();
  }
  console.log("用户购物车数据修改api",res);
}
async function increaseNum_btn (cartItem:any) {
  if(cartItem.cartCommodityCount > 99) return;
  cartItem.cartCommodityCount ++;
  let params = {id:cartItem.id,cartCommodityCount:cartItem.cartCommodityCount};
  let res = await reqUpdateUserCart(params);
  if(res.code === 200){
    //数量修改成功,重新计算数据
    calculateUserCart();
  }
  console.log("用户购物车数据修改api",res);
}
//全选复选框change事件
async function allSelectedChange_btn () {
  let list = cartList.value;
  let cartIds = [];
  list.forEach(item => {
    item.cartSelected = allSelected.value;
    cartIds.push(item.id);
  })
  //发请求更新数据，并重新进行计算
  let res = await reqUpdateUserCartSelectedBatch(cartIds,allSelected.value);
  if(res.code === 200) {
    //批量修改用户购物车选中状态,重新计算数据
    calculateUserCart();
  }
  console.log('批量修改用户购物车选中状态api',res);
}
//购物车每一项的选中事件
async function changeSelected_btn (cartItem:any) {
  let params = {id:cartItem.id,cartSelected:cartItem.cartSelected};
  let res = await reqUpdateUserCart(params);
  if(res.code === 200){
    //数量修改成功,重新计算数据
    calculateUserCart();
  }
  console.log("用户购物车数据修改api",res);
}
//删除按钮事件
function deleteCartItem_btn () {
  let list = cartList.value;
  if(list.every(item => item.cartSelected === false)) return showToast("未选择商品数据!");
  let cartIds = new Array();
  for(let i = 0; i < list.length; i++){
    if(list[i].cartSelected){
      cartIds.push(list[i].id);
    }
  }
  //console.log(cartIds);
  showConfirmDialog({title: '提示',message:'确定将选中的商品从购物车移除吗?此操作不可逆!'})
  .then(async () => {
    // on confirm
    let res = await reqDeleteUserCartBatch(cartIds);
    if(res.code === 200){
      //重新请求购物车数据列表
      showToast("移除成功!");
      getUserCartList();
    }
    console.log('购物车商品移除api(单条、批量)',res);
  })
  .catch(() => {
    // on cancel
    showToast("操作取消!");
  });
}
//提交订单按钮
function submitOrder_btn () {
  //检测是否有选择商品进行结算
  if(cartList.value.every(item => item.isSelected === false)) return showToast("未选择任何商品!");
  //路由跳转
  router.push("/create");
  //全局通信，将商品数据进行传递
  let productInfo = cartList.value.filter(item => item.cartSelected === true).map(item => {
    return {
      commodityId:item.cartCommodityId,
      commodityStandardId:item.cartCommodityStandardId,
      commodityStandardStr:item.commodityAttrName,
      commodityCount:item.cartCommodityCount,
      productName:item.commodityName,
      productImg:item.commodityImgs.split(","),
      productPrice:item.commodityAttrPrice
    }
  })
  setTimeout(() => {
    mitt.emit("orderInfo",{productInfo:productInfo});
  },100)
  //此处一定得延时 > 50ms,否则获取不到数据
}

//vue生命周期
onMounted(() => {
  getUserCartList();
})

//keep-alive缓存生命周期
onActivated(() => {
  //调用时机为首次挂载以及从缓存中重新被插入时
  console.log('cart component enter page!');
})
onDeactivated(() => {
  //在从 DOM 上移除、进入缓存以及组件卸载时调用
  console.log('cart component entry cache!');
})
onBeforeUnmount(() => {
  console.log('cart component is over!');
})
</script>

<style lang='less' scoped>
.cart-page{
  width: 375px;
  height: calc(100vh - 60px - 46px);
  // height: 560px;
  position: relative;
  top:47px;
  overflow: scroll;
  background: #eff2f5;

  /*未登录状态*/
  .cart-page-noLogin{
    width: 375px;
    height: 400px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #eff2f5;

    .noLogin-info{
      font-size: 14px;
      color: #9195a3;
    }

    .noLogin-button{
      width: 130px;
      height: 40px;
      margin: 20px 0;
      border-radius: 20px;
    }
  }
  /*已登录状态*/
  .cart-page-login{
    width: 375px;

    .login-cart-list{
      width: 375px;

      .cart-list-info{
        width: 375px;
        height: 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .info-left{
          font-size: 12px;
          .info-icon{
            margin: 0 5px;
            padding: 5px 10px;
            background-color: #9195a3;
            color: #fff;
          }
        }
        .info-right{
          margin-right: 20px;
          font-size: 12px;
          .active{
            color: #e61c1c;
          }
        }
      }

      /*购物车列表*/
      .cart-list-content{
        width: 375px;
        height: 465px;
        padding-bottom: 20px;
        overflow: auto;
        /**购物车中商品每一项 */
        .cart-list-content-item{
          width: 355px;
          height: 90px;
          margin: 10px auto;
          padding: 10px;
          box-sizing: border-box;
          border-radius: 10px;
          font-size: 14px;
          display: flex;
          align-items: center;
          background: #fff;

          img{
            width: 70px;
            height: 70px;
            margin: 0 30px;
          }

          .item-product-info{
            height: 70px;

            .info-desc{
              color: #000;
              font-size: 16px;
              margin-bottom: 15px;
            }

            .info-attr{
              display: inline;
              font-size: 12px;
              padding: 3px;
              background-color: #eff2f5;
              color: #9195a3;
            }

            .info-other{
              width: 180px;
              height: 25px;
              margin-top: 5px;
              line-height: 25px;
              display: flex;
              justify-content: space-between;

              .other-price{
                color: #f00;
              }

              .info-change-num{
                input{
                  width: 25px;
                  height: 20px;
                  margin: 0 10px;
                  text-align: center;
                  font-size: 12px;
                  border: none;
                  background-color: #eff2f5;
                }
              }
            }
          }
        }
      }
      /**购物车中没有商品数据 */
      .no-list{
          width: 375px;
          height: 465px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 14px;
      } 
    }
  } 
  /**底部固定功能区 */
  .cart-page-bar{
    width: 375px;
    height: 55px;
    position: absolute;
    bottom: 0;
    padding: 0 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    .bar-radio{
      font-size: 14px;
      color: #000;
    }
    .bar-total{
      font-size: 14px;
      color: #000;
      .total-text{
        font-size: 18px;
        font-weight: bold;
        color: #f00;
      }
    }
    .bar-btn{
      display:flex;
      .btn-amount{
        width: 105px;
        height: 40px;
      }
    }
    .bar-btns{
      display: flex;
      .btn-item{
        margin: 0 5px;
      }
    }
  }
}
</style>